import axios from 'axios';
import {ElMessage} from "element-plus";
import useUserStore from "@/store/modules/user";

// 第一步：利用axios对象的create方法，去创建axios实例
let request = axios.create({
    baseURL: import.meta.env.VITE_GLOB_API_URL,
    timeout: 5000
});

// 第二步：添加请求拦截器
request.interceptors.request.use((config) => {
    //config配置对象，headers属性请求头，经常给服务器传入token
    let userStore = useUserStore();
    if (userStore.token) {
        config.headers.token = userStore.token;
        // config.headers['Authorization'] = userStore.token;
        // config.headers['Content-Type'] = 'application/json';
    }
    return config;
});

// 第三步：添加响应拦截器
request.interceptors.response.use((response) => {
    return response.data;
}, (error) => {
    let message = '';
    let status = error.response.status;
    switch (status) {
        case  401:
            message = "Token过期"
            break;
        case  403:
            message = "无权访问"
            break;
        case  404:
            message = "请求地址错误"
            break;
        case  500:
            message = "服务器错误"
            break;
        default:
            message = "网络问题"
    }
    ElMessage({
        type: 'error',
        message
    })
    return Promise.reject(error);
})

export default request;